package com.example.wanghao.wangyixinwen.view;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by wanghao on 2016/5/16.
 */
public class CustomViewPager extends ViewPager {
    private static final float MIN_SCALE = 0.25f;//最小缩放值
    //动画中的第一个参数view
    private View left;//A页面
    private View right;//B页面
    private  Map<Integer,ImageView> images = new HashMap<>();

    public CustomViewPager(Context context) {
        super(context);
    }

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    //将viewpager的界面页面传递进来
    public void addChildView(ImageView iv, int position) {

        images.put(position,iv);
    }

    //删除已经销毁掉的界面
    public void removeChildView(int position) {
        images.remove(position);
    }

    @Override
    protected void onPageScrolled(int position, float offset, int offsetPixels) {
        super.onPageScrolled(position, offset, offsetPixels);
        System.out.println("position :" +position);
        System.out.println("offset :" +offset);
        System.out.println("offsetPixels :" +offsetPixels);
        
        left = images.get(position);//当前页面
        right = images.get(position + 1);
        
        startAnimation(left,right,position,offset,offsetPixels);
    }

    private void startAnimation(View left, View right, int position, float offset, int offsetPixels) {

        if (right != null){

            float translationx = -(getWidth() - offsetPixels);
            right.setTranslationX(translationx);

            //[0.75,1]
            //offset[0,1]
            float scaleFactor = MIN_SCALE
                    + (1 - MIN_SCALE) *  Math.abs(offset);
            right.setScaleX(scaleFactor);
            right.setScaleY(scaleFactor);
        }

        if (left != null){
            left.bringToFront();//让当前的页面显示在最上层
        }
    }
}
